// 主题系统
// 提供统一的主题管理、动态主题切换、自定义主题支持

import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { useGlobalStore } from '../../stores/globalStore';

// 主题配置接口
export interface ThemeConfig {
  name: string;
  displayName: string;
  description: string;
  author: string;
  version: string;
  colors: ThemeColors;
  typography: ThemeTypography;
  spacing: ThemeSpacing;
  shadows: ThemeShadows;
  borders: ThemeBorders;
  animations: ThemeAnimations;
  components: ComponentThemes;
}

// 颜色配置
export interface ThemeColors {
  // 主色调
  primary: ColorScale;
  secondary: ColorScale;
  accent: ColorScale;
  
  // 语义色彩
  success: ColorScale;
  warning: ColorScale;
  error: ColorScale;
  info: ColorScale;
  
  // 中性色彩
  gray: ColorScale;
  
  // 背景色
  background: {
    primary: string;
    secondary: string;
    tertiary: string;
    overlay: string;
    modal: string;
  };
  
  // 文本色
  text: {
    primary: string;
    secondary: string;
    tertiary: string;
    inverse: string;
    disabled: string;
  };
  
  // 边框色
  border: {
    primary: string;
    secondary: string;
    focus: string;
    error: string;
    success: string;
  };
  
  // 编辑器特定色彩
  editor: {
    background: string;
    foreground: string;
    selection: string;
    lineHighlight: string;
    cursor: string;
    gutter: string;
    gutterText: string;
  };
  
  // 语法高亮色彩
  syntax: {
    keyword: string;
    string: string;
    number: string;
    comment: string;
    function: string;
    variable: string;
    type: string;
    operator: string;
    punctuation: string;
  };
}

// 颜色等级
export interface ColorScale {
  50: string;
  100: string;
  200: string;
  300: string;
  400: string;
  500: string;
  600: string;
  700: string;
  800: string;
  900: string;
  950: string;
}

// 字体配置
export interface ThemeTypography {
  fontFamily: {
    sans: string[];
    serif: string[];
    mono: string[];
  };
  fontSize: {
    xs: string;
    sm: string;
    base: string;
    lg: string;
    xl: string;
    '2xl': string;
    '3xl': string;
    '4xl': string;
  };
  fontWeight: {
    light: number;
    normal: number;
    medium: number;
    semibold: number;
    bold: number;
  };
  lineHeight: {
    tight: number;
    normal: number;
    relaxed: number;
  };
  letterSpacing: {
    tight: string;
    normal: string;
    wide: string;
  };
}

// 间距配置
export interface ThemeSpacing {
  xs: string;
  sm: string;
  md: string;
  lg: string;
  xl: string;
  '2xl': string;
  '3xl': string;
  '4xl': string;
}

// 阴影配置
export interface ThemeShadows {
  sm: string;
  md: string;
  lg: string;
  xl: string;
  '2xl': string;
  inner: string;
  none: string;
}

// 边框配置
export interface ThemeBorders {
  width: {
    thin: string;
    normal: string;
    thick: string;
  };
  radius: {
    none: string;
    sm: string;
    md: string;
    lg: string;
    xl: string;
    full: string;
  };
}

// 动画配置
export interface ThemeAnimations {
  duration: {
    fast: string;
    normal: string;
    slow: string;
  };
  easing: {
    linear: string;
    easeIn: string;
    easeOut: string;
    easeInOut: string;
  };
}

// 组件主题配置
export interface ComponentThemes {
  button: ComponentTheme;
  input: ComponentTheme;
  panel: ComponentTheme;
  modal: ComponentTheme;
  tooltip: ComponentTheme;
  editor: ComponentTheme;
  [key: string]: ComponentTheme;
}

// 单个组件主题
export interface ComponentTheme {
  base: string;
  variants: Record<string, string>;
  sizes: Record<string, string>;
  states: Record<string, string>;
}

// 主题上下文
export interface ThemeContextValue {
  currentTheme: ThemeConfig;
  availableThemes: ThemeConfig[];
  setTheme: (themeName: string) => void;
  registerTheme: (theme: ThemeConfig) => void;
  createCustomTheme: (baseTheme: string, overrides: Partial<ThemeConfig>) => ThemeConfig;
  exportTheme: (themeName: string) => string;
  importTheme: (themeData: string) => void;
  isDark: boolean;
  toggleDarkMode: () => void;
}

// 默认浅色主题
const lightTheme: ThemeConfig = {
  name: 'light',
  displayName: '浅色主题',
  description: '默认浅色主题',
  author: 'CodeGraph Team',
  version: '1.0.0',
  colors: {
    primary: {
      50: '#eff6ff',
      100: '#dbeafe',
      200: '#bfdbfe',
      300: '#93c5fd',
      400: '#60a5fa',
      500: '#3b82f6',
      600: '#2563eb',
      700: '#1d4ed8',
      800: '#1e40af',
      900: '#1e3a8a',
      950: '#172554',
    },
    secondary: {
      50: '#f8fafc',
      100: '#f1f5f9',
      200: '#e2e8f0',
      300: '#cbd5e1',
      400: '#94a3b8',
      500: '#64748b',
      600: '#475569',
      700: '#334155',
      800: '#1e293b',
      900: '#0f172a',
      950: '#020617',
    },
    accent: {
      50: '#fdf4ff',
      100: '#fae8ff',
      200: '#f5d0fe',
      300: '#f0abfc',
      400: '#e879f9',
      500: '#d946ef',
      600: '#c026d3',
      700: '#a21caf',
      800: '#86198f',
      900: '#701a75',
      950: '#4a044e',
    },
    success: {
      50: '#f0fdf4',
      100: '#dcfce7',
      200: '#bbf7d0',
      300: '#86efac',
      400: '#4ade80',
      500: '#22c55e',
      600: '#16a34a',
      700: '#15803d',
      800: '#166534',
      900: '#14532d',
      950: '#052e16',
    },
    warning: {
      50: '#fffbeb',
      100: '#fef3c7',
      200: '#fde68a',
      300: '#fcd34d',
      400: '#fbbf24',
      500: '#f59e0b',
      600: '#d97706',
      700: '#b45309',
      800: '#92400e',
      900: '#78350f',
      950: '#451a03',
    },
    error: {
      50: '#fef2f2',
      100: '#fee2e2',
      200: '#fecaca',
      300: '#fca5a5',
      400: '#f87171',
      500: '#ef4444',
      600: '#dc2626',
      700: '#b91c1c',
      800: '#991b1b',
      900: '#7f1d1d',
      950: '#450a0a',
    },
    info: {
      50: '#f0f9ff',
      100: '#e0f2fe',
      200: '#bae6fd',
      300: '#7dd3fc',
      400: '#38bdf8',
      500: '#0ea5e9',
      600: '#0284c7',
      700: '#0369a1',
      800: '#075985',
      900: '#0c4a6e',
      950: '#082f49',
    },
    gray: {
      50: '#f9fafb',
      100: '#f3f4f6',
      200: '#e5e7eb',
      300: '#d1d5db',
      400: '#9ca3af',
      500: '#6b7280',
      600: '#4b5563',
      700: '#374151',
      800: '#1f2937',
      900: '#111827',
      950: '#030712',
    },
    background: {
      primary: '#ffffff',
      secondary: '#f9fafb',
      tertiary: '#f3f4f6',
      overlay: 'rgba(0, 0, 0, 0.5)',
      modal: '#ffffff',
    },
    text: {
      primary: '#111827',
      secondary: '#4b5563',
      tertiary: '#9ca3af',
      inverse: '#ffffff',
      disabled: '#d1d5db',
    },
    border: {
      primary: '#e5e7eb',
      secondary: '#d1d5db',
      focus: '#3b82f6',
      error: '#ef4444',
      success: '#22c55e',
    },
    editor: {
      background: '#ffffff',
      foreground: '#1f2937',
      selection: '#dbeafe',
      lineHighlight: '#f9fafb',
      cursor: '#1f2937',
      gutter: '#f3f4f6',
      gutterText: '#6b7280',
    },
    syntax: {
      keyword: '#7c3aed',
      string: '#059669',
      number: '#dc2626',
      comment: '#6b7280',
      function: '#2563eb',
      variable: '#1f2937',
      type: '#c026d3',
      operator: '#374151',
      punctuation: '#4b5563',
    },
  },
  typography: {
    fontFamily: {
      sans: ['Inter', 'system-ui', 'sans-serif'],
      serif: ['Georgia', 'serif'],
      mono: ['JetBrains Mono', 'Consolas', 'Monaco', 'monospace'],
    },
    fontSize: {
      xs: '0.75rem',
      sm: '0.875rem',
      base: '1rem',
      lg: '1.125rem',
      xl: '1.25rem',
      '2xl': '1.5rem',
      '3xl': '1.875rem',
      '4xl': '2.25rem',
    },
    fontWeight: {
      light: 300,
      normal: 400,
      medium: 500,
      semibold: 600,
      bold: 700,
    },
    lineHeight: {
      tight: 1.25,
      normal: 1.5,
      relaxed: 1.75,
    },
    letterSpacing: {
      tight: '-0.025em',
      normal: '0em',
      wide: '0.025em',
    },
  },
  spacing: {
    xs: '0.25rem',
    sm: '0.5rem',
    md: '1rem',
    lg: '1.5rem',
    xl: '2rem',
    '2xl': '3rem',
    '3xl': '4rem',
    '4xl': '6rem',
  },
  shadows: {
    sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)',
    md: '0 4px 6px -1px rgba(0, 0, 0, 0.1)',
    lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1)',
    xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1)',
    '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)',
    inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)',
    none: 'none',
  },
  borders: {
    width: {
      thin: '1px',
      normal: '2px',
      thick: '4px',
    },
    radius: {
      none: '0',
      sm: '0.25rem',
      md: '0.375rem',
      lg: '0.5rem',
      xl: '0.75rem',
      full: '9999px',
    },
  },
  animations: {
    duration: {
      fast: '150ms',
      normal: '300ms',
      slow: '500ms',
    },
    easing: {
      linear: 'linear',
      easeIn: 'cubic-bezier(0.4, 0, 1, 1)',
      easeOut: 'cubic-bezier(0, 0, 0.2, 1)',
      easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',
    },
  },
  components: {
    button: {
      base: 'inline-flex items-center justify-center rounded-md font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none',
      variants: {
        primary: 'bg-primary-600 text-white hover:bg-primary-700 focus:ring-primary-500',
        secondary: 'bg-secondary-100 text-secondary-900 hover:bg-secondary-200 focus:ring-secondary-500',
        outline: 'border border-primary-300 text-primary-700 hover:bg-primary-50 focus:ring-primary-500',
        ghost: 'text-primary-700 hover:bg-primary-100 focus:ring-primary-500',
      },
      sizes: {
        sm: 'h-8 px-3 text-sm',
        md: 'h-10 px-4 text-base',
        lg: 'h-12 px-6 text-lg',
      },
      states: {
        loading: 'opacity-70 cursor-wait',
        disabled: 'opacity-50 cursor-not-allowed',
      },
    },
    input: {
      base: 'block w-full rounded-md border border-gray-300 px-3 py-2 text-sm placeholder-gray-400 focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500',
      variants: {
        default: 'bg-white text-gray-900',
        filled: 'bg-gray-50 text-gray-900',
        flushed: 'border-0 border-b-2 rounded-none px-0',
      },
      sizes: {
        sm: 'h-8 text-sm',
        md: 'h-10 text-base',
        lg: 'h-12 text-lg',
      },
      states: {
        error: 'border-red-300 focus:border-red-500 focus:ring-red-500',
        success: 'border-green-300 focus:border-green-500 focus:ring-green-500',
        disabled: 'bg-gray-100 cursor-not-allowed',
      },
    },
    panel: {
      base: 'bg-white rounded-lg border border-gray-200 shadow-sm',
      variants: {
        default: 'bg-white',
        elevated: 'shadow-lg',
        outlined: 'border-2',
      },
      sizes: {
        sm: 'p-3',
        md: 'p-4',
        lg: 'p-6',
      },
      states: {
        loading: 'opacity-70',
        error: 'border-red-300 bg-red-50',
      },
    },
    modal: {
      base: 'fixed inset-0 z-50 flex items-center justify-center',
      variants: {
        default: 'bg-black bg-opacity-50',
        blur: 'backdrop-blur-sm bg-black bg-opacity-30',
      },
      sizes: {
        sm: 'max-w-md',
        md: 'max-w-lg',
        lg: 'max-w-2xl',
        xl: 'max-w-4xl',
      },
      states: {
        entering: 'animate-in fade-in duration-200',
        exiting: 'animate-out fade-out duration-200',
      },
    },
    tooltip: {
      base: 'absolute z-50 px-2 py-1 text-sm text-white bg-gray-900 rounded shadow-lg',
      variants: {
        default: 'bg-gray-900 text-white',
        light: 'bg-white text-gray-900 border border-gray-200',
      },
      sizes: {
        sm: 'px-2 py-1 text-xs',
        md: 'px-3 py-2 text-sm',
        lg: 'px-4 py-3 text-base',
      },
      states: {
        visible: 'opacity-100',
        hidden: 'opacity-0',
      },
    },
    editor: {
      base: 'font-mono text-sm leading-relaxed',
      variants: {
        default: 'bg-white text-gray-900',
        dark: 'bg-gray-900 text-gray-100',
      },
      sizes: {
        sm: 'text-xs',
        md: 'text-sm',
        lg: 'text-base',
      },
      states: {
        focused: 'ring-2 ring-primary-500',
        readonly: 'bg-gray-50 cursor-not-allowed',
      },
    },
  },
};

// 创建深色主题（基于浅色主题）
const darkTheme: ThemeConfig = {
  ...lightTheme,
  name: 'dark',
  displayName: '深色主题',
  description: '默认深色主题',
  colors: {
    ...lightTheme.colors,
    background: {
      primary: '#0f172a',
      secondary: '#1e293b',
      tertiary: '#334155',
      overlay: 'rgba(0, 0, 0, 0.8)',
      modal: '#1e293b',
    },
    text: {
      primary: '#f8fafc',
      secondary: '#cbd5e1',
      tertiary: '#64748b',
      inverse: '#0f172a',
      disabled: '#475569',
    },
    border: {
      primary: '#334155',
      secondary: '#475569',
      focus: '#3b82f6',
      error: '#ef4444',
      success: '#22c55e',
    },
    editor: {
      background: '#0f172a',
      foreground: '#f8fafc',
      selection: '#1e40af',
      lineHighlight: '#1e293b',
      cursor: '#f8fafc',
      gutter: '#334155',
      gutterText: '#94a3b8',
    },
  },
};

// 主题上下文
const ThemeContext = createContext<ThemeContextValue | null>(null);

// 主题提供者组件
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const globalStore = useGlobalStore();
  const [themes, setThemes] = useState<ThemeConfig[]>([lightTheme, darkTheme]);
  const [currentTheme, setCurrentTheme] = useState<ThemeConfig>(lightTheme);

  // 从全局设置中获取主题
  useEffect(() => {
    const themeName = globalStore.settings.theme === 'system' 
      ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
      : globalStore.settings.theme === 'dark' ? 'dark' : 'light';
    
    const theme = themes.find(t => t.name === themeName) || lightTheme;
    setCurrentTheme(theme);
    applyThemeToDOM(theme);
  }, [globalStore.settings.theme, themes]);

  // 应用主题到DOM
  const applyThemeToDOM = useCallback((theme: ThemeConfig) => {
    const root = document.documentElement;
    
    // 设置CSS变量
    Object.entries(theme.colors).forEach(([category, colors]) => {
      if (typeof colors === 'object' && colors !== null) {
        Object.entries(colors).forEach(([key, value]) => {
          if (typeof value === 'string') {
            root.style.setProperty(`--color-${category}-${key}`, value);
          } else if (typeof value === 'object') {
            Object.entries(value).forEach(([subKey, subValue]) => {
              root.style.setProperty(`--color-${category}-${key}-${subKey}`, subValue);
            });
          }
        });
      }
    });

    // 设置字体变量
    Object.entries(theme.typography.fontFamily).forEach(([key, value]) => {
      root.style.setProperty(`--font-${key}`, value.join(', '));
    });

    // 设置其他变量
    Object.entries(theme.spacing).forEach(([key, value]) => {
      root.style.setProperty(`--spacing-${key}`, value);
    });

    // 设置主题类名
    root.className = theme.name === 'dark' ? 'dark' : 'light';
  }, []);

  // 设置主题
  const setTheme = useCallback((themeName: string) => {
    const theme = themes.find(t => t.name === themeName);
    if (theme) {
      setCurrentTheme(theme);
      globalStore.updateSetting('theme', themeName as any);
      applyThemeToDOM(theme);
    }
  }, [themes, globalStore, applyThemeToDOM]);

  // 注册主题
  const registerTheme = useCallback((theme: ThemeConfig) => {
    setThemes(prev => {
      const existing = prev.find(t => t.name === theme.name);
      if (existing) {
        return prev.map(t => t.name === theme.name ? theme : t);
      }
      return [...prev, theme];
    });
  }, []);

  // 创建自定义主题
  const createCustomTheme = useCallback((baseThemeName: string, overrides: Partial<ThemeConfig>): ThemeConfig => {
    const baseTheme = themes.find(t => t.name === baseThemeName) || lightTheme;
    return {
      ...baseTheme,
      ...overrides,
      colors: {
        ...baseTheme.colors,
        ...overrides.colors,
      },
      typography: {
        ...baseTheme.typography,
        ...overrides.typography,
      },
      components: {
        ...baseTheme.components,
        ...overrides.components,
      },
    };
  }, [themes]);

  // 导出主题
  const exportTheme = useCallback((themeName: string): string => {
    const theme = themes.find(t => t.name === themeName);
    if (!theme) {
      throw new Error(`Theme "${themeName}" not found`);
    }
    return JSON.stringify(theme, null, 2);
  }, [themes]);

  // 导入主题
  const importTheme = useCallback((themeData: string) => {
    try {
      const theme: ThemeConfig = JSON.parse(themeData);
      registerTheme(theme);
    } catch (error) {
      throw new Error('Invalid theme data');
    }
  }, [registerTheme]);

  // 切换深色模式
  const toggleDarkMode = useCallback(() => {
    const newTheme = currentTheme.name === 'dark' ? 'light' : 'dark';
    setTheme(newTheme);
  }, [currentTheme.name, setTheme]);

  const contextValue: ThemeContextValue = {
    currentTheme,
    availableThemes: themes,
    setTheme,
    registerTheme,
    createCustomTheme,
    exportTheme,
    importTheme,
    isDark: currentTheme.name === 'dark',
    toggleDarkMode,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
};

// 使用主题的Hook
export const useTheme = (): ThemeContextValue => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

// 获取组件主题的Hook
export const useComponentTheme = (componentName: string) => {
  const { currentTheme } = useTheme();
  return currentTheme.components[componentName] || currentTheme.components.button;
};

// 导出主题配置
export { lightTheme, darkTheme };
export type { ThemeConfig, ThemeColors, ComponentTheme };
